package com.lin;

/**
 * @Author zimingl
 * @Date 2023/4/29 20:26
 * @Description: 读写锁
 */
public class SynchronizedTest02 {
    public static void main(String[] args) {
        SharedData data = new SharedData();
        Writer writer = new Writer(data);
        Reader reader = new Reader(data);
        writer.start();
        reader.start();
    }
}

class SharedData {
    private int count = 0;

    // 使用synchronized关键字保证线程安全
    public synchronized void increment() {
        count++;
        System.out.println("Write: " + count);
    }

    // 使用synchronized关键字保证线程安全
    public synchronized int getCount() {
        System.out.println("Read: " + count);
        return count;
    }
}

class Writer extends Thread {
    private SharedData data;

    public Writer(SharedData data) {
        this.data = data;
    }

    public void run() {
        while (true) {
            data.increment();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Reader extends Thread {
    private SharedData data;

    public Reader(SharedData data) {
        this.data = data;
    }

    public void run() {
        while (true) {
            data.getCount();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
